package xcx

import (
	"log"
	"tempSend/models"
	"tempSend/pkg/cache"
	"time"

	"github.com/medivhzhan/weapp/message/template"
	"github.com/medivhzhan/weapp/token"
)

//获取token，并设置缓存时间
func GetAccessToken() string {
	mpInfo := models.GetMpInfo()
	var err error
	var cacheKey string = mpInfo.Appid + ":access_token"
	tok, _ := cache.Get(cacheKey)
	if tok == "" {
		// 获取次数有限制 获取后请缓存
		tok, _, err = token.AccessToken(mpInfo.Appid, mpInfo.Appsecret)
		if err != nil {
			log.Fatal(err)
		}

		cache.Set(cacheKey, tok, 1*time.Hour)
	}

	return tok
}

//发送模板消息
func SendTemplate(openid, templateID, page, formID string, msg template.Message) error {
	token := GetAccessToken()

	err := template.Send(openid, templateID, page, formID, msg, "", token)
	return err
}

//获取要推送的模板消息
